######### Makefile COMMON ########
#c 还是 c++
EXTENSION = c
#gcc 还是 g++
CC = clang

# 分析工具
ANALYSING_TOOL = ./build/llvmassignment

#源文件路径 空格 可以继续添如 src src1 src2
SUBDIR = tests
#.o文件存放路径
OBJ = ./tests
#.d文件存放路径
DEP = ./tests/dep

#编译器的选项
CFLAGS += -emit-llvm -O0 -g3
CFLAGS_NO_DEBUG += -emit-llvm -O0

#后面的内容都不需要修改
CXX_SOURCES = $(foreach dir,$(SUBDIR), $(wildcard $(dir)/*.$(EXTENSION)))
CXX_OBJECTS = $(patsubst  %.$(EXTENSION), $(OBJ)/%.bc, $(notdir $(CXX_SOURCES)))
CXX_OBJECTS_NODEBUG = $(patsubst  %.$(EXTENSION), $(OBJ)/%.opt.bc, $(notdir $(CXX_SOURCES)))
CXX_IR = $(patsubst  %.$(EXTENSION), $(OBJ)/%.opt.ll, $(notdir $(CXX_SOURCES)))
CXX_LOG = $(patsubst  %.$(EXTENSION), $(OBJ)/%.log, $(notdir $(CXX_SOURCES)))

# 对所有的.bc 文件使用分析工具进行分析
test: $(CXX_OBJECTS) $(ANALYSING_TOOL)
	@$(foreach file, $(CXX_OBJECTS), \
		echo "\033[33m $(file) function call analysing  \033[0m"; \
		$(ANALYSING_TOOL) $(file) > $(subst .bc,.log,$(file)) 2>&1; \
		echo "\033[32m $(file) analysing successed \033[0m"; )


$(ANALYSING_TOOL): src/use-def.cpp
	@echo "\033[33m rebuild $(ANALYSING_TOOL) .. \033[0m"
	@cd build && make && cd ..
	@echo "\033[32m build $(ANALYSING_TOOL) successed \033[0m"

#自定义补充规则, gnu make 自带的规则库无法推导, 告诉make工具如何生成.bc文件
$(OBJ)/%.bc: $(SUBDIR)/%.$(EXTENSION)
	@echo $< "is compling into" $@
	@$(CC) -Xclang -disable-O0-optnone -c $(CFLAGS) $< -o $@
	@$(CC) -Xclang -disable-O0-optnone -c $(CFLAGS_NO_DEBUG) $< -o $(subst .bc,.opt.bc,$@)
	@opt -S -mem2reg $(subst .bc,.opt.bc,$@) -o $(subst .bc,.opt.ll,$@)
	@echo $< "\033[32m complied successed! \033[0m"

.PHONY:clean
clean:
	@-rm  -f  $(CXX_OBJECTS) ${CXX_OBJECTS_NODEBUG} $(CXX_IR) $(CXX_LOG)
